package org.bl.chat.service;

import cn.hutool.core.bean.BeanUtil;
import org.bl.chat.dao.MessageDao;
import org.bl.chat.model.dto.MessageDTO;
import org.bl.chat.model.po.MessageDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class MessageService {

    @Resource
    private MessageDao messageDao;

    @Resource
    private MongoTemplate mongoTemplate;

    public List<MessageDTO> findByChannelId(String channelId, Integer page) {

        int pageSize = 20;
        int skip = (page - 1) * pageSize;
        Query query = new Query();
        query.addCriteria(Criteria.where("channelId").is(channelId));
        query.with(Sort.by(Sort.Direction.DESC, "createDate"));
        query.skip(skip);
        query.limit(pageSize);

        List<MessageDO> list = mongoTemplate.find(query, MessageDO.class);

        return BeanUtil.copyToList(list, MessageDTO.class);
    }

    public void save(MessageDO bean) {
        messageDao.save(bean);
    }
}
